//
//  XCAVFlashPlayer.m
//  TTLestening
//
//  Created by dllo on 16/3/28.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "XCAVFlashPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "Masonry.h"
#import <MediaPlayer/MediaPlayer.h>
#import "UIColor+Wonderful.h"
#import "KSBarrageView.h"

// 枚举值，包含水平移动方向和垂直移动方向
typedef NS_ENUM(NSInteger, PanDirection){
    PanDirectionHorizontalMoved, //横向移动
    PanDirectionVerticalMoved    //纵向移动
};


#define WIDGHT  self.frame.size.width
#define HEIGHT  self.frame.size.height

#define WIDGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667

#define WIDGHTA [UIScreen mainScreen].bounds.size.width
#define HEIGHTA [UIScreen mainScreen].bounds.size.height

@interface XCAVFlashPlayer ()

#warning 声音的属性还没写
@property (nonatomic, strong) UISlider *volumeViewSlider;
@property (nonatomic, strong)AVPlayerLayer *playerLayer;
@property (nonatomic, assign)BOOL isPlay; // 是否播放
@property (nonatomic, assign)BOOL isTap; // 是否隐藏播放功能按键
@property (nonatomic, assign) CGFloat totalMovieDuration; // 保存该视频资源的总时长，快进或快退的时候要用
@property (nonatomic, strong)NSString *url;
@property (nonatomic, assign) CGFloat cookTime; // 缓存的时间
@property (nonatomic, assign) CGFloat currentTime; // 当前播放的时间
@property (nonatomic, strong)UIView *boomView;
@property (nonatomic, strong)UISlider *progressSlider;
@property (nonatomic, strong)UIButton *playButton;
@property (nonatomic, strong)UILabel *timeLabel;
@property (nonatomic, strong)UIProgressView *cookProgress;
@property (nonatomic, strong)UIButton *allScreenButton;
@property (nonatomic, strong)UIButton *danmuButton;
@property (nonatomic, assign)BOOL isLandScape;
@property (nonatomic, assign)CGFloat width;
@property (nonatomic, assign)CGFloat height;
@property (nonatomic, strong)KSBarrageView *danMuView;

@end


@implementation XCAVFlashPlayer

+ (instancetype)sharedFlashPlayerWithFrame:(CGRect)frame {
    
    static XCAVFlashPlayer *flashPlayer = nil;
    static  dispatch_once_t predicate;
    
    dispatch_once(&predicate, ^{
        
        flashPlayer = [[XCAVFlashPlayer alloc] initWithFrame:frame];
        
    });
    
    
    return flashPlayer;
    
}

- (void)dealloc {


}
- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.width = WIDGHT;
        self.height = HEIGHT;
        [self createSubview];
        [self addTapGesture];
        [self addAutoLandScape];
        [self addNotificationEnd];
//        [self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//        
//        [self.playItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];   // 监听loadedTimeRanges属性
        
    }
    
    return self;
    
}

- (void)createSubview {
    
    self.backgroundColor = [UIColor blackColor];
    
    self.play = [AVPlayer playerWithPlayerItem:self.playItem];
    
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.play];;
    self.playerLayer.frame = self.frame;
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.layer insertSublayer:self.playerLayer atIndex:0];
    
    
    

    
    self.boomView = [[UIView alloc] init];
    [self addSubview:self.boomView];
    self.boomView.backgroundColor = [UIColor blackColor];
    
    [self.boomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.bottom.mas_equalTo(self);
        make.height.mas_equalTo(self.mas_height).multipliedBy(1. / 7.);
        
    }];
    
    
    self.danMuView = [[KSBarrageView alloc] init];
    [self addSubview:self.danMuView];
    self.danmuButton.backgroundColor = [UIColor orangeColor];
    [self.danMuView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self).equalTo(@20);
        make.bottom.mas_equalTo(self.boomView.mas_top).equalTo(@ -15);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        
    }];
    
    // 播放 button
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.boomView addSubview:self.playButton];
    //self.playButton.backgroundColor = [UIColor greenColor];
    [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting-5"] forState:UIControlStateNormal];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.boomView).mas_equalTo(@(5 * WIDGHTT));
        make.top.mas_equalTo(self.boomView).mas_equalTo(@(3 * HEIGHTT));
        make.bottom.mas_equalTo(self.boomView).mas_equalTo(@(- 3 * HEIGHTT));
        make.width.mas_equalTo(self.playButton.mas_height).multipliedBy(1. / 1.);
        
        
    }];
    
    // 全屏 button
    self.allScreenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.boomView addSubview:self.allScreenButton];
//    self.allScreenButton.backgroundColor = [UIColor redColor];
    
    [self.allScreenButton setImage:[UIImage imageNamed:@"iconfont-quanping"] forState:UIControlStateNormal];
    
    [self.allScreenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(self.boomView).equalTo(@(- 5 * WIDGHTT ));
        make.top.mas_equalTo(self.boomView).mas_equalTo(@(3 * HEIGHTT));
        make.bottom.mas_equalTo(self.boomView).mas_equalTo(@(- 3 * HEIGHTT));
        make.width.mas_equalTo(self.playButton.mas_height).multipliedBy(1. / 1.);
        
    }];

    // 弹幕 button
    
    self.danmuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:self.danmuButton];
//    self.danmuButton.backgroundColor = [UIColor whiteColor];
    [self.danmuButton setImage:[UIImage imageNamed:@"iconfont-danmu"] forState:UIControlStateNormal];
    
    [self.danmuButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self).equalTo(@20);
        make.right.mas_equalTo(self).equalTo(@(- 5 * WIDGHTT));
        make.width.mas_equalTo(self.playButton.mas_width);
        make.height.mas_equalTo(self.playButton.mas_height);
        
    }];

    self.timeLabel = [[UILabel alloc] init];
    [self.boomView addSubview:self.timeLabel];
   // self.timeLabel.backgroundColor = [UIColor blueColor];
    self.timeLabel.textColor = [UIColor whiteColor];
    
    // progressView
    
    self.cookProgress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    [self.boomView addSubview:self.cookProgress];
    self.cookProgress.tintColor = [UIColor lightGrayColor];
    self.cookProgress.trackTintColor = [UIColor whiteColor];
    
    // [self.cookProgress setProgress:0.5 animated:NO];
    
    self.progressSlider = [[UISlider alloc] init];
    [self.cookProgress addSubview:self.progressSlider];
    self.progressSlider.minimumTrackTintColor = Wonderful_BlueColor3 ;
    self.progressSlider.maximumTrackTintColor = [UIColor clearColor];
    
    [self.cookProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.playButton.mas_right).equalTo(@(5 * WIDGHTT));
        make.right.mas_equalTo(self.allScreenButton.mas_left).equalTo(@(- 5 * WIDGHTT));
        make.top.mas_equalTo(self.boomView.mas_top).equalTo(@(5 * HEIGHTT));
        make.height.mas_equalTo(2);
    }];
    
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"iconfont-yuandian"] forState:UIControlStateNormal];
    
    [self.progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.playButton.mas_right).equalTo(@(5 * WIDGHTT));
        make.right.mas_equalTo(self.allScreenButton.mas_left).equalTo(@(- 5 * WIDGHTT));
        make.top.mas_equalTo(self.boomView.mas_top).equalTo(@(5 * HEIGHTT));
        make.height.mas_equalTo(1);
    
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.playButton.mas_right).equalTo(@(5 * WIDGHTT));
        make.width.mas_equalTo(self.mas_width).multipliedBy(1. / 2.);
        make.top.mas_equalTo(self.cookProgress.mas_bottom).equalTo(@(5 * HEIGHTT));
        //make.top.mas_equalTo(self.progressSlider.mas_bottom).equalTo(@(0));
        make.bottom.mas_equalTo(self.boomView.mas_bottom).equalTo(@(- 5 * HEIGHTT));
        
    }];

    
    
    
     [[NSNotificationCenter defaultCenter] postNotificationName:AVPlayerItemPlaybackStalledNotification object:nil];
    
    [self.playButton addTarget:self action:@selector(playOrPasu:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.allScreenButton addTarget:self action:@selector(allScreenAction:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)addAutoLandScape {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(roteAction:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];

}

- (void)roteAction:(NSNotification *) noti {

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    // 向右横屏
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        
        [self setPlayerLayerFrame];
    }
    // 向左横屏
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        
        [self setPlayerLayerFrame];
        
    }if (orientation == UIInterfaceOrientationPortrait) {
        [self setPlayerLayerFramePortrait];
        
    }
    
  
}

- (void)setPlayerLayerFrame {

    self.frame = CGRectMake(0, 0, WIDGHTA, HEIGHTA);
    self.playerLayer.frame = CGRectMake(0, 0, WIDGHTA, HEIGHTA);

}

- (void)setPlayerLayerFramePortrait {

    self.frame = CGRectMake(0, 0, self.width, self.height);
    self.playerLayer.frame = CGRectMake(0, 0, self.width, self.height);

}


- (void)addTapGesture {

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAction:)];
    [self addGestureRecognizer:tap];

}

/**点击隐藏功能*/
- (void)dismissAction:(UITapGestureRecognizer *) tap {

    if(self.isTap == NO) {
    
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.boomView.alpha = 0;
            self.danmuButton.alpha = 0;
            
        }];
    
    } else {
    
        [UIView animateWithDuration:0.5 animations:^{
            
            self.boomView.alpha = 0.8;
            self.danmuButton.alpha = 1;
            
        }];
      
    }
    
    self.isTap = !self.isTap;

}


/**播放或者暂停 button*/
- (void)playOrPasu:(UIButton *) button {
    
    if (self.isPlay) {
        
        NSLog(@"播放");
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting-5"] forState:UIControlStateNormal];
        
        [self.play play];
        
    }else {
        
        NSLog(@"暂停");
        
        [self.play pause];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-3"] forState:UIControlStateNormal];
        
        
    }
    
    self.isPlay = !self.isPlay;
    
}


- (void)passUrl:(NSString *)url {
    
    
   // NSLog(@"2222222222%@", url);
    self.url = url;
    
    [self.cookProgress setProgress:0];
    NSString *urlStr=[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *netUrl=[NSURL URLWithString:urlStr];
        
    self.playItem = [AVPlayerItem playerItemWithURL:netUrl];
    
    [self.play replaceCurrentItemWithPlayerItem:self.playItem];
    
    [self.play play];
   
    
    [self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.playItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];   // 监听loadedTimeRanges属性
    [self addProgressObserver];
    
  //  [self.playItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];

    //获取系统音量
    [self configureVolume];

        [[NSNotificationCenter defaultCenter] addObserverForName:AVPlayerItemPlaybackStalledNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
    
            if ((self.cookTime - self.currentTime) >= 2.0) {
                // NSLog(@"ddddddddd");
                [self.play play];
    
            } else {
    
                [self.play pause];
    
            }
    
        }];

}
//获取系统音量
- (void)configureVolume
{
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    _volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            _volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    
    // 使用这个category的应用不会随着手机静音键打开而静音，可在手机静音下播放声音
    NSError *setCategoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance]
                    setCategory: AVAudioSessionCategoryPlayback
                    error: &setCategoryError];
    
    if (!success) { /* handle the error in setCategoryError */ }
}



/**弹幕数组赋值*/
- (void)passDamuArray:(NSArray *)danmuku {

   // NSLog(@"%ld", danmuku.count);
    
    [self.danMuView setDataArray:danmuku];
    
    [self.danMuView start];

}


// 获取视频总时长
- (void)addProgressObserver {
    
    //    //设置(1,1) 设置每秒执行一次
    
    __weak XCAVFlashPlayer *avFlashPlay = self;
    [avFlashPlay.play addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        
        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(avFlashPlay.playItem.duration);
        
        //当前时间
        avFlashPlay.currentTime = CMTimeGetSeconds(avFlashPlay.play.currentTime);
        
        //倒计时
        CGFloat rem = duration - avFlashPlay.currentTime;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)avFlashPlay.currentTime/60 ,(int)avFlashPlay.currentTime%60];
        
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
        avFlashPlay.timeLabel.text = timeStr;
        avFlashPlay.timeLabel.font = [UIFont systemFontOfSize:15];
        avFlashPlay.timeLabel.adjustsFontSizeToFitWidth = YES;
        //保存总时长用于手动快进和快退
        avFlashPlay.totalMovieDuration = duration;
        
        //设置进度值 当前时间/总时长
        avFlashPlay.progressSlider.value = avFlashPlay.currentTime / duration;
        
        [avFlashPlay.progressSlider addTarget:avFlashPlay action:@selector(toAnyTime:) forControlEvents:UIControlEventValueChanged];
        
    }];
    
}

/**是否横屏*/
- (void)allScreenAction:(UIButton *) button {

    if (!self.isLandScape) {
        
        if ( [[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)] ) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = UIInterfaceOrientationLandscapeRight;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }
        
        
    } else {
        
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val =UIInterfaceOrientationPortrait;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }
      
    }

    self.isLandScape = !self.isLandScape;

}

// 滑动条调到任意时间播放
- (void)toAnyTime:(UISlider *)time {
    
    UISlider *slider = time;
    
    //获取当前时间
    double currentTime = self.totalMovieDuration * slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.play seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        
        [self.play play];
        
    }];
    
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
            
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        self.cookTime = [self availableDuration];// 计算缓冲进度
        // NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = self.playItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.cookProgress setProgress:self.cookTime / totalDuration animated:YES];
    }
}

- (NSTimeInterval)availableDuration {
    
    NSArray *loadedTimeRanges = [[self.play currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}


////在监听播放器状态中处理比较准确
- (void)playerItemPlaybackStalled:(NSNotification *)notification
{
    // 这里网络不好的时候，就会进入，不做处理，会在playbackBufferEmpty里面缓存之后重新播放
    NSLog(@"buffing-----buffing");
    
}


/** 添加播放完毕的观察者 */
- (void)addNotificationEnd {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)playEnd:(NSNotification *) end {
    
    NSLog(@"播放完毕");
    
    [self.playItem removeObserver:self forKeyPath:@"status"];
    [self.playItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    
    [self passUrl:self.url];
    
}



/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
